package com.cloud.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 返回前端的数据包装
 * @author mi
 */
public class ResultData {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    /*
     * 调用结果
     */
    private boolean success;

    /*
     * 错误或成功代码
     */
    private int code;

    /*
     * 状态码
     */
    private int status;

    /*
     * 服务器端返回消息
     */
    private String msg;

    /*
     * 数据对象
     */
    private Object data;


    public ResultData() {
    }

    public boolean success() {
        return success;
    }

    public int getCode() {
        return code;
    }

    public ResultData setCode(int code) {
        this.code = code;
        return this;
    }
    public int getStatus() {
        return status;
    }

    public ResultData setStatus(int status) {
        this.status = status;
        return this;
    }

    public boolean isSuccess() {
        return success;
    }

    public ResultData setSuccess(boolean success) {
        this.success = success;
        return this;
    }

    /**
     * 分解code返回提示信息 未设置code时，
     * 如果有msg信息直接返回msg，
     * 否则默认返回500错误并打印日志提示开发者
     */
    public String getMsg() {
        if (code <= 0) {
            if (msg != null && !"".equals(msg)) {
                return msg;
            }
            code = MsgCode.CODE_ERROR;
            logger.warn("Msg Code is Invalid !");
        }
        return msg;
    }

    public ResultData setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public static ResultData result(boolean result) {
        return new ResultData().setSuccess(result)
                .setCode(result ? MsgCode.CODE : MsgCode.CODE_ERROR)
                .setMsg(result ? MsgCode.DEFAULT_CODE_MSG : MsgCode.CODE_ERROR_MSG);
    }

    public Object getData() {
        return data;
    }

    public ResultData setData(Object data) {
        this.data = data;
        return this;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("ResultData [success=");
        stringBuilder.append(success);
        stringBuilder.append(", code=");
        stringBuilder.append(code);
        stringBuilder.append(", status=");
        stringBuilder.append(status);
        stringBuilder.append(", msg=");
        stringBuilder.append(msg);
        stringBuilder.append(", data=");
        stringBuilder.append(data);
        stringBuilder.append("]");
        return stringBuilder.toString();
    }
}
